package com.xingxing.Service;

import com.google.gson.Gson;
import com.xingxing.Bean.User;
import com.xingxing.Dao.UserDao;
import com.xingxing.Util.HashUtil;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/Login")
public class Login extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setHeader("Content-type", "text/html; charset=UTF-8");
        PrintWriter out = response.getWriter();
        HttpSession session = request.getSession();
        Map<String, Object> mapOut = new HashMap<>();
        User user = null;
        if (session.getAttribute("user") == null) {
            String userAccount = null;
            String userPassword = null;
            if (request.getParameter("userAccount") != null) {
                userAccount = request.getParameter("userAccount");
                userPassword = request.getParameter("userPassword");
            } else {
                StringBuffer sb = new StringBuffer();
                BufferedReader br = new BufferedReader(
                        new InputStreamReader((ServletInputStream) request.getInputStream(), "utf-8"));
                String temp;
                while ((temp = br.readLine()) != null) {
                    sb.append(temp);
                }
                br.close();
                Map<String, Object> mapIn = new HashMap<>();
                mapIn = new Gson().fromJson(sb.toString(), mapIn.getClass());
                userAccount = (String) mapIn.get("userAccount");
                userPassword = (String) mapIn.get("userPassword");
            }
            userPassword = HashUtil.getSHA256StrJava(userAccount + userPassword);
            user = UserDao.find(userAccount);
            if (user == null) {
                mapOut.put("status", "账号不存在");
            } else {
                if (user.getUserPassword().equals(userPassword)) {
                    mapOut.put("status", "登录成功");
                    mapOut.put("user", user);
                    session.setAttribute("user", user);
                } else {
                    mapOut.put("status", "密码错误");
                }
            }
        } else {
            mapOut.put("status", "已经登陆");
            user = (User) session.getAttribute("user");
            mapOut.put("user", user);
        }
        String str = new Gson().toJson(mapOut);
        out.println(str);
        out.flush();
        out.close();
    }
}